package com.leyou.item.service;

import com.leyou.common.dto.SpecGroupDTO;
import com.leyou.common.dto.SpecParamDTO;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroupDTO> findGroupByCid(Long id){
        SpecGroup record = new SpecGroup();
        record.setCid(id);
        List<SpecGroup> specGroups = specGroupMapper.select(record);
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specGroups,SpecGroupDTO.class);
    }

    public List<SpecParamDTO> findParams(Long gid, Long cid, Boolean searching){
        if(gid == null && cid == null){
            throw  new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setSearching(searching);
        List<SpecParam> specParams = specParamMapper.select(record);
        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specParams,SpecParamDTO.class);
    }

    public List<SpecGroupDTO> findGroupByCidWithParams(Long id) {
        //根据商品分类查询出分类下的规格组列表
        List<SpecGroupDTO> groups = findGroupByCid(id);
        //根据商品分类查询出分类下的规格参数列表
        List<SpecParamDTO> params = findParams(null, id, null);
        //使用流式编程对params根据groupId分组
        Map<Long, List<SpecParamDTO>> paramsMap = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //把对应的规格组下的规格参数赋值进去
        groups.forEach(group->{
            group.setParams(paramsMap.get(group.getId()));
        });

//        groups.forEach(group->{
//            params.forEach(param->{
//                if(group.getId()==param.getGroupId()){
//                    group.getParams().add(param);
//                }
//            });
//        });
        return groups;
    }
}
